mod commands;
mod database;
mod logging;
mod shortcuts;
mod state;
mod tray;
mod error;
mod validation;
mod performance;

// Re-export for testing
pub use database::*;
pub use validation::*;
pub use error::*;
pub use performance::*;

// Removed unused modules that were not integrated:
// - performance: Complex monitoring system not used in main app
// - plugins: Plugin system framework not integrated
// - security: Security modules not used in main app
// - updater: Auto-update system not integrated

use crate::state::AppState;
use std::sync::Mutex;
use tauri::Manager;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    // Initialize logging
    env_logger::Builder::from_default_env()
        .filter_level(log::LevelFilter::Info)
        .init();

    log::info!("Starting Multi-Platform Crawler application");

    tauri::Builder::default()
        // Add plugins
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_global_shortcut::Builder::new().build())
        .plugin(tauri_plugin_window_state::Builder::default().build())

        // Setup application state
        .setup(|app| {
            // Get app data directory
            let data_dir = app
                .path()
                .app_data_dir()
                .expect("Failed to get app data directory");

            // Initialize application state
            let app_state = AppState::new(data_dir.clone())
                .expect("Failed to initialize application state");

            // Store state in Tauri's managed state
            let app_state_mutex = Mutex::new(app_state);
            app.manage(app_state_mutex);

            // Create system tray
            if let Err(e) = tray::create_tray(&app.handle()) {
                log::error!("Failed to create system tray: {}", e);
            }

            // Register global shortcuts
            if let Err(e) = shortcuts::register_global_shortcuts(&app.handle()) {
                log::error!("Failed to register global shortcuts: {}", e);
            }

            log::info!("Application setup completed successfully");

            // Add some sample logs to database for testing
            if let Some(state) = app.try_state::<Mutex<AppState>>() {
                if let Ok(app_state) = state.lock() {
                    let _ = app_state.database.add_log("INFO", "Application started successfully", Some("startup"));
                    let _ = app_state.database.add_log("DEBUG", &format!("Database initialized at {:?}", data_dir), Some("database"));
                    let _ = app_state.database.add_log("WARN", "This is a sample warning message for testing", Some("test"));
                    let _ = app_state.database.add_log("ERROR", "This is a sample error message for testing (not a real error)", Some("test"));
                }
            }

            // Also log to console
            log::debug!("Debug: Database initialized at {:?}", data_dir);
            log::warn!("Warning: This is a sample warning message for testing");
            log::error!("Error: This is a sample error message for testing (not a real error)");

            // Simulate some application events in background
            let app_handle = app.handle().clone();
            std::thread::spawn(move || {
                std::thread::sleep(std::time::Duration::from_secs(2));
                log::info!("Background task: Application fully loaded");
                log::debug!("Debug: Memory usage check completed");

                // 添加到数据库
                if let Some(state) = app_handle.try_state::<Mutex<AppState>>() {
                    if let Ok(app_state) = state.lock() {
                        let _ = app_state.database.add_log("INFO", "Application fully loaded", Some("background"));
                        let _ = app_state.database.add_log("DEBUG", "Memory usage check completed", Some("system"));
                    }
                }

                std::thread::sleep(std::time::Duration::from_secs(3));
                log::info!("Background task: Periodic health check");
                log::warn!("Warning: High memory usage detected (simulated)");

                if let Some(state) = app_handle.try_state::<Mutex<AppState>>() {
                    if let Ok(app_state) = state.lock() {
                        let _ = app_state.database.add_log("INFO", "Periodic health check", Some("health"));
                        let _ = app_state.database.add_log("WARN", "High memory usage detected (simulated)", Some("system"));
                    }
                }

                std::thread::sleep(std::time::Duration::from_secs(5));
                log::info!("Background task: Auto-save completed");
                log::debug!("Debug: Configuration synchronized");

                if let Some(state) = app_handle.try_state::<Mutex<AppState>>() {
                    if let Ok(app_state) = state.lock() {
                        let _ = app_state.database.add_log("INFO", "Auto-save completed", Some("storage"));
                        let _ = app_state.database.add_log("DEBUG", "Configuration synchronized", Some("config"));
                    }
                }

                std::thread::sleep(std::time::Duration::from_secs(8));
                log::info!("Background task: Database optimization completed");
                log::warn!("Warning: Disk space running low (simulated)");

                if let Some(state) = app_handle.try_state::<Mutex<AppState>>() {
                    if let Ok(app_state) = state.lock() {
                        let _ = app_state.database.add_log("INFO", "Database optimization completed", Some("database"));
                        let _ = app_state.database.add_log("WARN", "Disk space running low (simulated)", Some("system"));
                    }
                }

                std::thread::sleep(std::time::Duration::from_secs(10));
                log::error!("Error: Network connection timeout (simulated)");
                log::info!("Background task: Attempting to reconnect...");

                if let Some(state) = app_handle.try_state::<Mutex<AppState>>() {
                    if let Ok(app_state) = state.lock() {
                        let _ = app_state.database.add_log("ERROR", "Network connection timeout (simulated)", Some("network"));
                        let _ = app_state.database.add_log("INFO", "Attempting to reconnect...", Some("network"));
                    }
                }

                std::thread::sleep(std::time::Duration::from_secs(2));
                log::info!("Background task: Connection restored successfully");

                if let Some(state) = app_handle.try_state::<Mutex<AppState>>() {
                    if let Ok(app_state) = state.lock() {
                        let _ = app_state.database.add_log("INFO", "Connection restored successfully", Some("network"));
                    }
                }
            });

            Ok(())
        })

        // Register command handlers
        .invoke_handler(tauri::generate_handler![
            // App info commands
            commands::get_app_info,
            commands::get_system_info,

            // Configuration commands
            commands::get_app_config,
            commands::set_app_config,

            // Test commands
            commands::test_command,
            commands::generate_test_logs,
            commands::generate_old_test_logs,

            // Logging commands
            commands::get_logs,
            commands::clear_logs,
            commands::get_log_stats,

            // File system commands
            commands::read_text_file,
            commands::write_text_file,
            commands::file_exists,
            commands::is_text_file,
            commands::create_directory,
            commands::read_directory,
            commands::get_current_directory,
            commands::get_home_directory,

            // Window management commands
            commands::toggle_window_visibility,
            commands::center_window,

            // Utility commands
            commands::generate_uuid,
            commands::get_current_timestamp,

            // Process management commands
            commands::get_process_info,

            // Application lifecycle commands
            commands::quit_app,
            commands::restart_app,

            // Performance monitoring commands
            commands::get_performance_metrics,
            commands::get_performance_report,
            commands::start_performance_event,
            commands::end_performance_event,
            commands::set_custom_metric,
            commands::increment_custom_metric,
            commands::get_performance_history,
            commands::clear_performance_data,
        ])

        // Handle application events
        .on_window_event(|window, event| {
            match event {
                tauri::WindowEvent::CloseRequested { api, .. } => {
                    // Prevent default close behavior and hide window instead
                    api.prevent_close();
                    let _ = window.hide();
                    log::info!("Window hidden instead of closed");
                }
                tauri::WindowEvent::Focused(focused) => {
                    log::debug!("Window focus changed: {}", focused);
                }
                _ => {}
            }
        })

        // Run the application
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
